<template>
  <div class="art_list">
    <van-pull-refresh
      v-model="isRefreshLoading"
      :success-text="refreshSuccessText"
      :success-duration="1500"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <articleItem
          v-for="(article, index) in list"
          :key="index"
          :article="article"
        />
        <!-- <van-cell
          v-for="(art, index) in list"
          :key="index"
          :title="art.title"
        /> -->
      </van-list>
    </van-pull-refresh>

  </div>
</template>

<script>
import { getArtList } from '@/api/art.js'
import articleItem from '@/components/article_item'

export default {
  name: 'ArtList',
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [], // 存取列表数据的数组
      loading: false, // 控制加载中loading 的状态
      finished: false, // 控制数据加载结束的状态
      error: false, // 是否加载失败
      timestamp: null,
      isRefreshLoading: false,
      refreshSuccessText: ''
    }
  },
  components: {
    articleItem
  },
  methods: {
    async onLoad () {
      // 1.请求获取数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      try {
        const { data } = await getArtList({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now()
        })
        // 2.把请求结果数据放到list数组中
        const { results } = data.data
        // 数组的展开操作符
        this.list.push(...results)

        // 3.加载状态结束
        this.loading = false

        // 4.数据全部加载完成
        if (results.length) {
          //  更新获取下一页的时间戳
          this.timestamp = data.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (err) {
        this.$toast('获取文章失败')
        this.loading = false // 关闭 loading 效果
        this.error = true // 开启错误提示
      }
    },
    async onRefresh () {
      try {
        const { data } = await getArtList({
          channel_id: this.channel.id,
          timestamp: Date.now()
        })
        // 2.把请求结果数据放到list数组中
        const { results } = data.data
        // 数组的展开操作符
        this.list.unshift(...results)

        // 3.加载状态结束
        this.isRefreshLoading = false

        // 4.提示成功
        this.refreshSuccessText = `刷新成功，更新了${results.length}条数据`
      } catch (err) {
        console.log(err)
        this.isRefreshLoading = false // 关闭下拉刷新的 loading 状态
        this.$toast('刷新失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.art_list {
  height: 79vh;
  overflow-y: auto;
}
</style>
